package edu.calpoly.android.echoes;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.util.Log;

public class saveList extends Activity implements SaveView.OnSaveChangeListener {
	
	/**
	 * Contains the list of Saves the Activity will present to the user.
	 **/
	protected Cursor m_arrSaveList;
	
	/**
	 * Adapter used to bind an AdapterView to List of Saves.
	 */
	protected SaveCursorAdapter m_saveAdapter;
	
	/**
	 * ViewGroup used for maintaining a list of Views that each display Saves.
	 **/
	protected ListView m_vwSaveLayout;
	
	/**
	 * Database of Saves the user can view, add to, and remove from.
	 */
	protected ShapeDBAdapter m_saveDB;
	
	/**
	 * Key used for storing and retrieving the text in m_vwSaveEditText in 
	 * savedInstanceState.
	 */
	protected static final String SAVED_EDIT_TEXT = "m_vwSaveEditText";
	
	
	protected static final int LOAD_SAVE_MENUITEM = Menu.FIRST;
	protected static final int REMOVE_SAVE_MENUITEM = LOAD_SAVE_MENUITEM + 1;
	protected static final int RENAME_SAVE_MENUITEM = REMOVE_SAVE_MENUITEM + 1;
	
	private Context m_context;
	private AudioPlayer m_audioPlayer;
	
	private long nameID = -1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Initialize the ContentView
		initLayout();
		
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		m_context = getBaseContext();
        m_audioPlayer = new AudioPlayer(m_context);
		
		m_saveDB = new ShapeDBAdapter(this);
		m_saveDB.open();
		
		m_arrSaveList = m_saveDB.getSavesCursor();
		startManagingCursor(m_arrSaveList);

		// Initialize the list of jokes from the strings.xml resource file
		/*m_nFilter = R.id.show_all_menuitem;
		m_arrFilteredJokeList = new ArrayList<Joke>();*/

		m_saveAdapter = new SaveCursorAdapter(this, m_arrSaveList);
		m_vwSaveLayout.setAdapter(m_saveAdapter);
		m_vwSaveLayout.setOnItemLongClickListener(m_saveAdapter);
		registerForContextMenu(m_vwSaveLayout);
		
		m_saveAdapter.setOnSaveChangeListener(this);

		/*String[] resJokes = res.getStringArray(R.array.jokeList);
		for (int ndx = 0; ndx < resJokes.length; ndx++) {
			addJoke(new Joke(resJokes[ndx], m_strAuthorName));
		}*/
		
		
		

		// Initialize the "Add Joke" listeners
		//initAddSaveListeners();
	}
	
	/**
	 * Method used to encapsulate the code that initializes and sets the Layout
	 * for this Activity.
	 */
	protected void initLayout() {
		setContentView(R.layout.listview);
		m_vwSaveLayout = (ListView) findViewById(R.id.saveListViewGroup);
		m_vwSaveLayout.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	}


	public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, view, menuInfo);

		MenuItem load = menu.add(Menu.NONE, LOAD_SAVE_MENUITEM, Menu.NONE, "Load Map");
		load.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			public boolean onMenuItemClick(MenuItem arg0) {
				long saveID = m_saveAdapter.getSelectedID();
				int save = (int) saveID;
				Log.e("onCreateContextMenu", "load item number " + saveID);
				m_saveDB.loadGame(save);
				
				setContentView(new DrawView(m_context, m_audioPlayer, m_saveDB, false));
			/*	m_jokeDB.removeJoke(jokeID);
				m_arrJokeList.requery();
				m_jokeAdapter.notifyDataSetChanged();*/
				return true;
			}
		});
		
		MenuItem remove = menu.add(Menu.NONE, REMOVE_SAVE_MENUITEM, Menu.NONE, "Remove Map");
		remove.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			public boolean onMenuItemClick(MenuItem arg0) {
				long saveID = m_saveAdapter.getSelectedID();
				//int save = (int) saveID;
				Log.e("onCreateContextMenu", "remove item number" + saveID);
				//displayData();
				m_saveDB.removeGame(saveID);
				m_arrSaveList.requery();
				return true;	
			}
		});
		
		MenuItem rename = menu.add(Menu.NONE, RENAME_SAVE_MENUITEM, Menu.NONE, "Rename Map");
		rename.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			public boolean onMenuItemClick(MenuItem arg0) {
				nameID = m_saveAdapter.getSelectedID();
				
				Intent myIntent = new Intent(m_context, RenameView.class);
				myIntent.putExtra("oldName", m_saveAdapter.getSelectedName());
				startActivityForResult(myIntent, 1);
				
				//int save = (int) saveID;
				Log.e("onCreateContextMenu", "rename item number" + nameID);
				//displayData();
				//m_saveDB.removeGame(saveID);
				return true;	
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_OK && requestCode == 1) {
			String name = data.getStringExtra("newName");
			m_saveDB.renameGame(name, nameID);
		}
	}
	
/*	private void displayData() {
		ArrayList<MyDrawableShapes> temp = m_saveDB.getAllShapes(m_saveDB.currGame());
		for(MyDrawableShapes mS : temp) {
			if(mS instanceof MyCircle) {
				MyCircle circle = (MyCircle) mS;
				Log.d("Circle", circle.getX() + " " + circle.getY() + " " + circle.getR());
			}
			if(mS instanceof MyRectangle) {
				MyRectangle rect = (MyRectangle) mS;
				Log.d("Rectangle", rect.getLeft() + " " + rect.getTop() + " " + rect.getRight() + " " + rect.getBottom());
			}
		}
	}*/
	/**
	 * Method used to encapsulate the code that initializes and sets the Event
	 * Listeners which will respond to requests to "Add" a new Joke to the list.
	 */
	/*protected void initAddJokeListeners() {
		m_vwJokeButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				String jokeText = m_vwJokeEditText.getText().toString(); 
				if (!jokeText.equals("")) {
					addJoke(new Joke(jokeText, m_strAuthorName));
					m_vwJokeEditText.setText("");
				}
			}
		});
		m_vwJokeEditText.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View view, int keyCode, KeyEvent event) {
				String jokeText = m_vwJokeEditText.getText().toString();
				if (!jokeText.equals("") && event.getAction() == KeyEvent.ACTION_DOWN && 
				 (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER)) { 
					addJoke(new Joke(jokeText ,m_strAuthorName));
					m_vwJokeEditText.setText("");
					return true;
				}
				if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(m_vwJokeEditText.getWindowToken(), 0);
					return true;
				}
				return false;
			}
		});
	}*/
	
	/**
	 * Method used for encapsulating the logic necessary to properly add a new
	 * Joke to m_arrJokeList, and display it on screen.
	 * 
	 * @param joke
	 *            The Joke to add to list of Jokes.
	 */
	/*protected void addSave(String s) {
		// Add joke
		m_saveDB.insertSave(s);
		m_arrSaveList.requery();
		
		//Possibly remove
		m_arrFilteredJokeList.add(joke);
		m_jokeAdapter.notifyDataSetChanged();

		// Hide Soft Keyboard
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(m_vwJokeEditText.getWindowToken(), 0);
	}*/


	public void onSaveChanged(SaveView view, String save) {
		// TODO Auto-generated method stub
		m_saveDB.updateSave(save);
		m_arrSaveList.requery();
	}

}
